<!--
 * @Description: 巡查任务管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="77"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column
          prop="inspectionTaskName"
          label="巡查任务名称"
          min-width="180"
        />
        <el-table-column prop="inspectionRouteName" label="巡查路线" />
        <el-table-column prop="employeeName" label="巡查人" />
        <el-table-column
          prop="generateTime"
          :formatter="dateFormat"
          label="巡查时间"
        />
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.inspectionTaskId" slot-scope="scope">
            <el-button
              v-if="judgePermission(77, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(77, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '巡查任务信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="巡查任务名称:" prop="inspectionTaskName" class="w50p">
            <el-input
              v-model="formData.inspectionTaskName"
              placeholder="请输入巡查任务名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="巡查线路选择:" prop="inspectionRouteId" class="w50p">
            <el-select
              v-model="formData.inspectionRouteId"
              clearable
              filterable
              @change="inspection"
            >
              <el-option
                v-for="item in patrolLine"
                :key="item.inspectionRouteId"
                :label="item.inspectionRouteName"
                :value="item.inspectionRouteId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="巡查人:" prop="personNo" class="w50p">
            <el-select
              v-model="formData.personNo"
              clearable
              filterable
              @change="employee"
            >
              <el-option
                v-for="(item, index) in staffData"
                :key="index"
                :label="item.person.name"
                :value="item.personNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务执行时间" prop="generateTime" class="w50p">
            <el-date-picker
              v-model="formData.generateTime"
              type="datetime"
              placeholder="请输入任务生成时间"
              clearable
              value-format="timestamp"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import InspectionTask from "@/api/digital-operation/patrol-info-manage/patrol-task-manage";
import staffManage from "@/api/digital-operation/personnel-cost-mansge/staff-manage";
import patrolInfoManage from "@/api/digital-operation/patrol-info-manage/patrol-line-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
// import { getToken } from "@/utils/auth";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
export default {
  name: "PatrolTaskManage",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
    StartTimeEndTimeSelectionBox
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '巡查任务名称',
          prop: 'inspectionTaskName',
          type: 'input',
        }, {
          label: '巡查路线',
          prop: 'inspectionRouteId',
          type: 'select',
          options: [], // patrolLine
          optionKey: { label: 'inspectionRouteName', value: 'inspectionRouteId' },
        }, {
          label: '巡查人',
          prop: 'employeeName',
          type: 'select',
          options: [], // staffData
          optionKey: { label: 'personName', value: 'personNo' },
        }, {
          label: '巡查时间',
          prop: 'date',
          type: 'daterange',
        }, 
      ],
      searchlist: {},
      inspectionTaskName: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      staffData: [],
      patrolLine: [],
      inspectionRouteId: "",
      employeeName: "",
      rules: {
        inspectionTaskName: [
          { required: true, message: "请输入巡查计划名称", trigger: "blur" }
        ],
        inspectionRouteId: [
          { required: true, message: "请选择巡查线路", trigger: "change" }
        ],
        personNo: [
          { required: true, message: "请选择巡查人", trigger: "change" }
        ],
        generateTime: [
          { required: true, message: "请选择时间", trigger: "change" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    this.getstaffManageList();
    this.$nextTick(() => {
      // this.employeeName = getToken("account");
      // this.staffData.push({ employeeName: getToken("account") })
      // console.log(this.staffData)
      this.search();
    });
  },
  mounted() {
    //  表格数据
    // this.getTableDataList();
  },
  methods: {
    getTableDataList() {
      this.tableData = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          inspectionTaskName: this.searchlist.inspectionTaskName || undefined,
          inspectionRouteId: this.searchlist.inspectionRouteId || undefined,
          beforeFlagList: [2, 3],
          checkFlag: false,
          employeeName: this.searchlist.employeeName || undefined,
          dataTimeStart : this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          dataTimeEnd: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          organizationNo: sessionStorage.organizationNo
        }
      };
      InspectionTask.getInspectionTaskList(params).then(res => {
        this.loading = false;
        let data = res.data;
        // console.log(data);
        if (data) {
          this.tableData = data.content;
          this.totalSize = data.totalElements;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    getstaffManageList() {
      // 巡查人 员工
      staffManage.getStaffListByCondition().then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值数组
        this.staffData = data;
        let list = data.map(el => {
          return { personName: el.person.name, personNo: el.person.personNo }
        })
        this.setOptions(this.formConfig, 'employeeName', list)
        // this.staffData.unshift({ employeeName: getToken("account") })
      });
      // 巡查线路 条件查询
      patrolInfoManage.inspectionRouteCondition().then(res => {
        let data = res.data;
        // 赋值数组
        this.patrolLine = data;
        this.setOptions(this.formConfig, 'inspectionRouteId', data)
        // console.log(this.patrolLine);
      });
    },
    employeeDa(e) {
      //   if (!e) {
      //     this.employeeName = getToken("account");
      //     // console.log(this.staffData)
      //     this.search()
      //   }
    },
    employee(e) {
      let obj = this.staffData.find(item => item.personNo === e);

      // this.staffData.forEach(element => {
      // if (element.personNo === e) {
      this.$set(this.formData, "employeeName", obj.person.name);
      // }
      // });
    },
    inspection(e) {
      this.patrolLine.forEach(element => {
        if (element.inspectionRouteId === e) {
          this.$set(
            this.formData,
            "inspectionRouteName",
            element.inspectionRouteName
          );
        }
      });
    },
    // 时间转换
    dateFormat(row, colnum) {
      if (row.inspectionTaskId) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD");
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    selectable(row, index) {
      // console.log(row)
      return row.beforeFlag !== 2; // 通过某个值来进行判断，规定那一行的选择框被禁用
    },

    add() {
      this.canInput = true;
      this.formData = {};
      this.openDialog("add");
    },
    handleEdit(row) {
      //  TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify(row));
      //   this.formData.employeeId = row.employeeId;
      // console.log(row)
      if (this.formData.beforeFlag === 2) {
        this.addActive = true;
        this.editActive = false;
        this.saveActive = false;
        this.delActive = false;
        this.cancelActive = false;
        this.canInput = false;
        this.$message.warning("自动任务不可修改！");
      } else {
        this.addActive = false;
        this.editActive = true;
        this.saveActive = false;
        this.delActive = false;
        this.cancelActive = true;
        this.canInput = false;
      }
      // this.$refs.formData.resetFields();/**/
      // this.openDialog('edit');
    },
    // cancel(){
    //   this.formData = {};
    //   this.closeDialog();
    // },
    handleSelectionChange(list) {
      this.inspectionTaskIdList = [];
      this.inspectionTaskIdList = list.map(item => item.inspectionTaskId);
      if (this.inspectionTaskIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage(formData) {
      InspectionTask.delInspectionTaskInfo(this.inspectionTaskIdList).then(
        res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            // this.$refs[formData].resetFields();
            this.getTableDataList();
            this.resetActionBar();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        }
      );
    },
    handleDelete(row) {
      // InspectionTask.delInspectionTaskInfo([row.inspectionTaskId]).then(
      //   res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       // this.$refs[formData].resetFields();
      //       this.getTableDataList();
      //       this.resetActionBar();
      //     } else {
      //       this.$message.warning(res.msg || '删除失败');
      //     }
      //   }
      // );
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          InspectionTask.delInspectionTaskInfo([row.inspectionTaskId]).then(
            res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.getTableDataList();
                this.resetActionBar();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            }
          );
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            InspectionTask.editInspectionTaskInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // if (this.formData.inspectionTaskId) {
            //   delete this.formData.inspectionTaskId
            // }
            this.formData.organizationNo = sessionStorage.organizationNo;
            this.formData.checkFlag = false;
            InspectionTask.addInspectionTaskInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
.staff-manage {
  width: 100%;
  height: 100%;
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
  }
  ::v-deep .el-input__inner {
    background-color: transparent;
    color: #fff;
    // border-radius: 5px;
    border-color: #6ecae3;
  }
  ::v-deep .el-form-item__label {
    min-width: 120px !important;
    text-align: end;
  }
  .common-layout {
    border: 1px solid $borderColor;
    height: calc(100% - #{$actionBarHeight + 10});
    padding: 20px;
    .search-box {
      display: flex;
      align-items: center;
      margin: 0 0 10px 0;
      .label-input {
        display: flex;
        align-items: center;
        // .input {
        //   // .el-input {
        //   //   width: 300px;
        //   //   ::v-deep .el-input__inner {
        //   //     // border-radius: 5px;
        //   //   }
        //   // }
        // }
        .label {
          width: 120px !important;
          white-space: nowrap;
        }
      }
      .search {
        display: flex;
        align-items: center;
        img {
          height: 30px;
        }
      }
    }
    .content {
      height: calc(100% - 50px);
      margin: 10px 0;
      display: flex;
      .left-box {
        width: 59%;
        height: 100%;
      }
      .table-box {
        height: calc(100% + 20px);
        position: relative;
        overflow-y: auto;
        //   border-radius: 8px;
        .el-table {
          background-color: transparent;
          color: #fff;
          // border-radius: 12px;
        }
      }
      .right-box {
        width: 39%;
        // height:100%;
        height: calc(100% - 50px);
        margin-left: 2%;
        border: 1px dashed rgba($color: #fff, $alpha: 0.6);
        border-radius: 10px;
        padding: 1% 2%;
        .form {
          overflow-x: auto;
          height: 100%;
          width: 100%;
          // border-top: 1px solid $borderColor;
          padding-top: 20px;
          .el-form {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            .el-form-item {
              .sort-box {
                display: inline-block;
                // width: 60px;
                transform: rotateY(180deg);
                .sort {
                  padding: 0 5px;
                  transform: rotate(-90deg);
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
